package com.miao.im.support.exception;

import com.miao.im.common.BizCode;
import com.miao.im.common.Constant;
import com.miao.im.common.Message;
import com.miao.im.common.annotation.SocketAdvice;
import com.miao.im.common.annotation.SocketExceptionHandler;
import com.miao.im.common.enums.Command;
import com.miao.im.model.ErrorResponseModel;
import com.miao.im.server.session.SessionContext;
import com.miao.im.server.session.SessionManager;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/19 16:57
 * @Description:
 */
@SocketAdvice
@Slf4j
public class SocketGlobalExceptionResolver {

    @SocketExceptionHandler(AuthenticationException.class)
    public void authEx(AuthenticationException ex, SessionContext sessionContext) {
        this.sendErrorMsg(ex.getCode(), ex.getMessage(), sessionContext);
    }

    @SocketExceptionHandler(BizException.class)
    public void bizEx(BizException ex, SessionContext sessionContext) {
        this.sendErrorMsg(ex.getCode(), ex.getMessage(), sessionContext);
    }

    @SocketExceptionHandler({Exception.class})
    public void otherEx(Exception ex, SessionContext sessionContext) {
        this.sendErrorMsg(BizCode.SERVER_ERROR, "系统异常，请稍后重试！", sessionContext);
    }

    private void sendErrorMsg(int code, String msg, SessionContext sessionContext) {
        ErrorResponseModel.ErrorResponse errorResponse = ErrorResponseModel.ErrorResponse.newBuilder()
                .setCode(code)
                .setMessage(msg)
                .build();
        Message response = Message.writeResponse(Constant.APP_VERSION, 0, Command.ERROR.getCode(), errorResponse.toByteArray());
        SessionManager.send(sessionContext, response);
    }
}
